from django.http import HttpResponseRedirect
from django.views.generic.list_detail import object_list, object_detail
from django.views.generic.create_update import create_object, update_object

from events.models import Event, Participant

from django_undo.utils import save_undo

def message_processor(request):
    """
    A context processor that adds a message from the session to the template context.
    It then deletes the message from the session
    """
    try:
        message = request.session['message']
        del request.session['message']
    except KeyError:
        message = None

    return {'message': message}

def list(request):
    return object_list(request,
                       queryset=Event.objects.order_by('id'),
                       template_object_name="event",
                       template_name="events/event_list.html",
                       paginate_by=15)

def detail(request, event_id):
    return object_detail(request,
                         queryset=Event.objects.all(),
                         object_id=event_id,
                         template_name="events/detail.html",
                         template_object_name='event',
                         extra_context={'participants': Participant.objects.filter(event__id__exact=event_id)})

def create(request):
    return create_object(request,
                         Event,
                         template_name="events/create.html")


def edit(request, event_id):
    event = Event.objects.get(id=event_id)
    id = save_undo(request, event)
    request.session['message'] = 'Event updated. <a href="/undo/%s/">undo</a>' % id
    return update_object(request,
                         Event,
                         object_id=event_id,
                         template_name="events/edit.html")

def delete(request, event_id):
    event = Event.objects.get(id=event_id)
    id = save_undo(request, event, redirect_to=u'/')
    request.session['message'] = 'Event deleted. <a href="/undo/%s/">undo</a>' % id
    event.delete()
    return HttpResponseRedirect("/")

def signup(request, event_id):
    return create_object(request,
                         Participant,
                         template_name="events/signup.html",
                         extra_context={'event': Event.objects.get(id=event_id)})
